# -*- coding: utf-8 -*-

import hashlib
import os
import re
import socket
import time


def create_class_instance(class_name, *args, **kwargs):
    (module_name, class_name) = class_name.rsplit('.', 1)
    module_meta = __import__(module_name, globals(), locals(), [class_name])
    class_meta = getattr(module_meta, class_name)
    result = class_meta(*args, **kwargs)

    return result


def add_items_into_dict(target, path='', **kwargs):
    def get_dict_item(di, pl):
        return di if not pl else get_dict_item(di[pl.pop(0)], pl)

    di = target if not path else get_dict_item(target, path.split(':'))

    for k, v in kwargs.items():
        di[k] = v

    return target


def make_dirs(path):
    if path and not os.path.exists(path):
        os.makedirs(path)


def get_ip_address():
    ip = ''

    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect(('baidu.com', 80))
        (ip, port) = s.getsockname()
    except:
        pass
    finally:
        try:
            s.close()
        except:
            pass

    return ip


def get_file_path(file_var):
    return os.path.dirname(os.path.realpath(file_var))


def load_file(filename):
    with open(filename, 'r') as f:
        return f.read()


def ustr(string, encoding='unicode-escape'):
    return str(string).decode(encoding)


def current_ts():
    return int(time.time())


def current_date(fmt='%Y-%m-%d %H:%M:%S'):
    return time.strftime(fmt, time.localtime(time.time()))


def get_date(day_delta=0, fmt='%Y-%m-%d %H:%M:%S'):
    return time.strftime(fmt, time.localtime(time.time() + 60 * 60 * 24 * day_delta))


def str2ts(str_time, time_format='%Y-%m-%d %H:%M:%S'):
    str_time, _ = re.subn('\ \+[\d]+', '', str_time)

    return int(time.mktime(time.strptime(str_time, time_format)))


def ts2str(ts, time_format='%Y-%m-%d %H:%M:%S'):
    return time.strftime(time_format, time.localtime(ts))


def md5(src):
    m2 = hashlib.md5()
    m2.update(src)

    return m2.hexdigest()
